package com.wangwenjun.concurrency.chapter14.happenbefore;

import java.util.concurrent.TimeUnit;

/**
 * @Package: com.wangwenjun.concurrency.chapter14.happenbefore
 * @ClassName: UseHappenBefore
 * @Author: lujieni
 * @Description: happen before传递性规则跨线程,跨对象
 * @Date: 2021-03-22 10:46
 * @Version: 1.0
 */
public class UseHappenBefore02 {

    public static void main(String[] args) throws Exception {
        Bye bye = new Bye();
        Hello hello = new Hello(bye);
        new Thread(()->{
            while (bye.count == 0){
                int num = hello.num;//读取volatile对象:num
            }
        }).start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(()->{
            hello.change();
        }).start();
    }

    private static class Hello{
        Bye bye;
        volatile int num = 0;

        public Hello(Bye bye){
            this.bye = bye;
        }

        private void change(){
            bye.change();//修改另外一个对象中的属性
            num = 1;//写volatile对象:num
        }
    }

    private static class Bye{
        int count = 0;

        private void change(){
            count = 10;
        }


    }











}